from flask import Blueprint, render_template, jsonify, request, redirect, url_for, flash
from flask_login import login_required, current_user
from app.models import Teacher, Student, Course, Score
from app import db
import datetime
import pandas as pd
import numpy as np
from sqlalchemy import func

dashboard = Blueprint('dashboard', __name__)

@dashboard.route('/dashboard')
@login_required
def index():
    if isinstance(current_user, Teacher):
        return render_template('dashboard/teacher_dashboard.html')
    else:
        return render_template('dashboard/student_dashboard.html')

@dashboard.route('/api/scores/overview')
@login_required
def scores_overview():
    """返回总体成绩概览数据"""
    if isinstance(current_user, Teacher):
        # 教师能看到所有学生的数据
        student_ids = [s.id for s in Student.query.filter_by(teacher_id=current_user.id)]
        scores = Score.query.filter(Score.student_id.in_(student_ids)).all()
    else:
        # 学生只能看到自己的数据
        scores = Score.query.filter_by(student_id=current_user.id).all()
    
    # 按课程统计平均分
    course_avg = {}
    course_count = {}
    
    for score in scores:
        if score.course.name not in course_avg:
            course_avg[score.course.name] = 0
            course_count[score.course.name] = 0
        
        course_avg[score.course.name] += score.score_value
        course_count[score.course.name] += 1
    
    for course in course_avg:
        course_avg[course] = round(course_avg[course] / course_count[course], 2)
    
    # 按考试次数统计平均分
    test_avg = {}
    test_count = {}
    
    for score in scores:
        if score.test_number not in test_avg:
            test_avg[score.test_number] = 0
            test_count[score.test_number] = 0
        
        test_avg[score.test_number] += score.score_value
        test_count[score.test_number] += 1
    
    for test in test_avg:
        test_avg[test] = round(test_avg[test] / test_count[test], 2)
    
    return jsonify({
        'course_avg': [{'name': k, 'value': v} for k, v in course_avg.items()],
        'test_avg': [{'name': f'第{k}次考试', 'value': v} for k, v in sorted(test_avg.items())]
    })

@dashboard.route('/api/scores/distribution')
@login_required
def score_distribution():
    """返回成绩分布数据"""
    if isinstance(current_user, Teacher):
        # 教师能看到所有学生的数据
        student_ids = [s.id for s in Student.query.filter_by(teacher_id=current_user.id)]
        scores = Score.query.filter(Score.student_id.in_(student_ids)).all()
    else:
        # 学生只能看到自己的数据
        scores = Score.query.filter_by(student_id=current_user.id).all()
    
    # 成绩分布：0-60, 60-70, 70-80, 80-90, 90-100
    ranges = {
        '不及格(0-60)': 0,
        '及格(60-70)': 0,
        '良好(70-80)': 0,
        '优秀(80-90)': 0,
        '卓越(90-100)': 0
    }
    
    for score in scores:
        value = score.score_value
        if value < 60:
            ranges['不及格(0-60)'] += 1
        elif value < 70:
            ranges['及格(60-70)'] += 1
        elif value < 80:
            ranges['良好(70-80)'] += 1
        elif value < 90:
            ranges['优秀(80-90)'] += 1
        else:
            ranges['卓越(90-100)'] += 1
    
    return jsonify({
        'distribution': [{'name': k, 'value': v} for k, v in ranges.items()]
    })

@dashboard.route('/api/scores/trend')
@login_required
def score_trend():
    """返回成绩趋势数据"""
    course_id = request.args.get('course_id')
    
    if isinstance(current_user, Teacher):
        # 教师能看到所有学生的数据
        student_ids = [s.id for s in Student.query.filter_by(teacher_id=current_user.id)]
        
        if course_id:
            scores = Score.query.filter(
                Score.student_id.in_(student_ids),
                Score.course_id == course_id
            ).order_by(Score.test_number).all()
        else:
            scores = Score.query.filter(
                Score.student_id.in_(student_ids)
            ).order_by(Score.test_number).all()
    else:
        # 学生只能看到自己的数据
        if course_id:
            scores = Score.query.filter_by(
                student_id=current_user.id,
                course_id=course_id
            ).order_by(Score.test_number).all()
        else:
            scores = Score.query.filter_by(
                student_id=current_user.id
            ).order_by(Score.test_number).all()
    
    # 按课程和考试次数统计
    trend_data = {}
    
    for score in scores:
        course_name = score.course.name
        test_number = score.test_number
        
        if course_name not in trend_data:
            trend_data[course_name] = {}
        
        if test_number not in trend_data[course_name]:
            trend_data[course_name][test_number] = []
        
        trend_data[course_name][test_number].append(score.score_value)
    
    # 计算每门课程每次考试的平均分
    result = []
    for course, tests in trend_data.items():
        data = []
        for test_number in sorted(tests.keys()):
            avg_score = round(sum(tests[test_number]) / len(tests[test_number]), 2)
            data.append(avg_score)
        
        result.append({
            'name': course,
            'data': data
        })
    
    # 获取考试次数列表
    test_numbers = []
    for course, tests in trend_data.items():
        test_numbers.extend(list(tests.keys()))
    test_numbers = sorted(list(set(test_numbers)))
    test_labels = [f'第{num}次' for num in test_numbers]
    
    return jsonify({
        'series': result,
        'categories': test_labels
    })

@dashboard.route('/api/student/performance')
@login_required
def student_performance():
    """返回学生表现数据（仅教师可见）"""
    if not isinstance(current_user, Teacher):
        return jsonify({'error': '无权限访问'}), 403
    
    # 获取该教师所有的学生
    students = Student.query.filter_by(teacher_id=current_user.id).all()
    student_data = []
    
    for student in students:
        scores = Score.query.filter_by(student_id=student.id).all()
        if not scores:
            continue
            
        avg_score = sum(s.score_value for s in scores) / len(scores)
        max_score = max(s.score_value for s in scores)
        min_score = min(s.score_value for s in scores)
        
        student_data.append({
            'id': student.id,
            'name': student.name,
            'grade': student.grade,
            'avg_score': round(avg_score, 2),
            'max_score': max_score,
            'min_score': min_score,
            'score_count': len(scores)
        })
    
    return jsonify({'students': student_data})

@dashboard.route('/scores/manage', methods=['GET', 'POST'])
@login_required
def manage_scores():
    """管理成绩（仅教师可见）"""
    if not isinstance(current_user, Teacher):
        flash('只有教师可以管理成绩。')
        return redirect(url_for('dashboard.index'))
    
    if request.method == 'POST':
        student_id = request.form.get('student_id')
        course_id = request.form.get('course_id')
        score_value = request.form.get('score_value')
        test_number = request.form.get('test_number')
        
        # 验证学生是否是该教师的学生
        student = Student.query.filter_by(id=student_id, teacher_id=current_user.id).first()
        if not student:
            flash('无效的学生ID。')
            return redirect(url_for('dashboard.manage_scores'))
        
        # 验证课程是否存在
        course = Course.query.get(course_id)
        if not course:
            flash('无效的课程ID。')
            return redirect(url_for('dashboard.manage_scores'))
        
        # 检查是否已存在相同学生、课程和考试次数的成绩记录
        existing_score = Score.query.filter_by(
            student_id=student_id,
            course_id=course_id,
            test_number=test_number
        ).first()
        
        if existing_score:
            existing_score.score_value = float(score_value)
            existing_score.test_date = datetime.datetime.now()
            flash('成绩更新成功。')
        else:
            new_score = Score(
                student_id=student_id,
                course_id=course_id,
                score_value=float(score_value),
                test_number=int(test_number)
            )
            db.session.add(new_score)
            flash('成绩添加成功。')
        
        db.session.commit()
        return redirect(url_for('dashboard.manage_scores'))
    
    # 获取该教师的所有学生
    students = Student.query.filter_by(teacher_id=current_user.id).all()
    # 获取所有课程
    courses = Course.query.all()
    # 获取所有成绩记录
    scores = db.session.query(
        Score, Student.name.label('student_name'), Course.name.label('course_name')
    ).join(Student, Score.student_id == Student.id).join(
        Course, Score.course_id == Course.id
    ).filter(Student.teacher_id == current_user.id).order_by(Score.test_date.desc()).all()
    
    return render_template('dashboard/manage_scores.html', 
                          students=students, 
                          courses=courses, 
                          scores=scores) 